﻿using CallCenter.Biz;
using CallCenter.Common;
using CallCenter.Forms;
using Newtonsoft.Json;
using OWINServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace CallCenter
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 呼叫或被叫的号码
        /// </summary>
        private string phoneNumber;

        /// <summary>
        /// WebAPI 服务端 IP
        /// </summary>
        private string serverIP;

        /// <summary>
        /// Http 服务端端口
        /// </summary>
        private int serverPort;

        /// <summary>
        /// Web API 端口
        /// </summary>
        private string webAPIPort;

        /// <summary>
        /// 企业 ID
        /// </summary>
        private string enterpriceID;

        /// <summary>
        /// 硬件设备编号 AF ******
        /// </summary>
        private string account;

        /// <summary>
        /// 座席号
        /// </summary>
        private string positionNumber;

        /// <summary>
        /// 当前座席状态
        /// </summary>
        private PositionStatus currentStatus;

        /// <summary>
        /// 当前任务 ID
        /// </summary>
        private string currentTaskID;

        /// <summary>
        /// 当前呼入流水号
        /// </summary>
        private string currentCallNonce;

        /// <summary>
        /// 是否通话中
        /// </summary>
        private bool isBusy;

        private OWINTriggerEvent triggerEvent;

        /// <summary>
        /// 初始化配置
        /// </summary>
        private bool InitConfig()
        {
            currentStatus = PositionStatus.Offline;
            this.phoneNumber = "";

            this.serverPort = 88;

            this.serverIP = ConfigurationManager.AppSettings["ServerIP"];
            if (string.IsNullOrEmpty(serverIP))
            {
                return false;
            }

            // 接口端口
            this.webAPIPort = ConfigurationManager.AppSettings["WebAPIPort"];
            if (string.IsNullOrEmpty(webAPIPort))
            {
                return false;
            }

            // 座席号
            positionNumber = ConfigurationManager.AppSettings["PositionNumber"];
            if (string.IsNullOrEmpty(positionNumber))
            {
                return false;
            }

            return true;
        }

        private bool InitOWinServer()
        {
            try
            {
                string baseAddress = ConfigurationManager.AppSettings["WebAPIAddr"];
                if (string.IsNullOrEmpty(baseAddress))
                {
                    AppendMessage("WebAPIAddr 配置信息错误！");
                    return false;
                }

                triggerEvent = OWINStart.Start(baseAddress);
                triggerEvent.incomingEvent += IncomingCallProcess;
                triggerEvent.statusEvent += CommunicateStatusProcess;
                return true;
            }
            catch (Exception ex)
            {
                AppendMessage($"创建webAPI服务发生异常：{ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="text"></param>
        private void AppendMessage(string text)
        {
            if (!this.Created)
            {
                return;
            }

            this.BeginInvoke((MethodInvoker)delegate
            {
                // 更新 UI 控件的代码
                txtMsg.Multiline = true;      // 确保是多行模式
                txtMsg.WordWrap = true;       // 确保自动换行
                // txtMsg.AppendText(text + "\r\n"); // 添加文本并换行
                txtMsg.Text = text + $" ({DateTime.Now.ToString("HH:mm:ss")})" + "\r\n" + txtMsg.Text;
            });
        }

        /// <summary>
        /// 座席登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            CommonInterface comInter = new CommonInterface();

            // 获取企业信息
            var result = comInter.GetEnterpriseInfo($"{serverIP}:{webAPIPort}");
            if (result != null && result.Count > 0 && result.ContainsKey("enterid"))
            {
                enterpriceID = result["enterid"];
            }
            else
            {
                AppendMessage("获取企业信息失败！");
                return;
            }

            if (result.ContainsKey("Acount"))
            {
                account = result["Acount"];
            }
            else
            {
                AppendMessage("获取企业信息失败！");
                return;
            }

            // 登录
            var loginRes = comInter.PositionLogin($"{serverIP}:{webAPIPort}", enterpriceID);
            if (loginRes)
            {
                this.currentStatus = PositionStatus.Online;
                SetProcessLimit();

                AppendMessage("登录成功！");
            }
        }

        /// <summary>
        /// 设置页面操作按钮状态
        /// </summary>
        private void SetProcessLimit()
        {
            switch (currentStatus)
            {
                case PositionStatus.Online:
                    btnLogin.Enabled = false;
                    btnCall.Enabled = true;
                    btnHangup.Enabled = true;
                    btnLogout.Enabled = true;
                    break;

                case PositionStatus.Offline:
                    btnLogin.Enabled = true;
                    btnCall.Enabled = false;
                    btnHangup.Enabled = false;
                    btnLogout.Enabled = false;
                    break;

                case PositionStatus.Leave:
                    // 暂时未使用该状态
                    break;

            }
        }

        /// <summary>
        /// 外呼
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCall_Click(object sender, EventArgs e)
        {
            if (txtTelephone.Text == "" || !PhoneValidator.IsValidPhone(txtTelephone.Text))
            {
                AppendMessage("请输入正确的电话号码！");
                return;
            }

            this.phoneNumber = txtTelephone.Text.Trim().Replace(" ", "");

            OutgoingCall callInter = new OutgoingCall();
            currentTaskID = callInter.Call($"{serverIP}:{serverPort}", enterpriceID, phoneNumber);
            if (!string.IsNullOrEmpty(currentTaskID))
            {
                AppendMessage("呼叫成功！");
                isBusy = true;
            }
            else
            {
                AppendMessage("呼叫失败！");
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogout_Click(object sender, EventArgs e)
        {
            if (isBusy)
            {
                AppendMessage("正在通话中，无法离线。");
                return;
            }

            CommonInterface comInter = new CommonInterface();
            if (this.currentStatus == PositionStatus.Online)
            {
                if (comInter.PositionLogout($"{serverIP}:{webAPIPort}", this.enterpriceID))
                {
                    currentStatus = PositionStatus.Offline;
                    SetProcessLimit();

                    AppendMessage("离线成功！");
                }
                else
                {
                    AppendMessage("离线失败！");
                }

                return;
            }
            else
            {
                AppendMessage("该操作无效。");
            }
        }

        private void btnQuitSystem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 挂机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHangup_Click(object sender, EventArgs e)
        {
            if (!isBusy)
            {
                AppendMessage("目前没有接入话路。");
                return;
            }

            // 调用接口
            CommonInterface comInter = new CommonInterface();
            if (comInter.Hangup($"{serverIP}:{webAPIPort}", enterpriceID))
            {
                AppendMessage("挂机成功！");
                // 设置标志位
                isBusy = false;
                phoneNumber = "";
            }
            else
            {
                AppendMessage("挂机失败！");
                isBusy = false;
            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            if (!InitConfig())
            {
                AppendMessage("系统配置加载有错误，系统无法正常运行。");
                return;
            }
            else
            {
                AppendMessage("系统配置初始化完成。");
            }

            if (!InitOWinServer())
            {
                AppendMessage("呼入WebAPI初始化失败，系统无法正常运行。");
                return;
            }
            else
            {
                AppendMessage("呼入WebAPI初始化完成。");
            }
        }

        /// <summary>
        /// 呼入事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IncomingCallProcess(object sender, EventArgs e)
        {
            string requestMsg = triggerEvent.Message;
            if (string.IsNullOrEmpty(requestMsg))
            {
                return;
            }

            Dictionary<string, string> msgDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(requestMsg);
            if (msgDict != null && msgDict.Count > 0 && msgDict.ContainsKey("callNo"))
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    txtIncomingTel.Text = msgDict["callNo"];
                });

                this.phoneNumber = msgDict["callNo"];
            }

            // 振铃
            FrmIncoming frm = new FrmIncoming(phoneNumber);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                // 接通
                //IncomingCall incoming = new IncomingCall();
                //incoming.ImcomingCallControl($"{serverIP}:{webAPIPort}", enterpriceID);
                isBusy = true;         // 该部分不会执行
            }
            else
            {
                // 挂断
                btnHangup_Click(null, null);
                this.BeginInvoke((MethodInvoker)delegate
                {
                    txtIncomingTel.Text = "";
                });
            }
        }

        /// <summary>
        /// 话路状态推送消息处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommunicateStatusProcess(object sender, EventArgs e)
        {
            AppendMessage("收到话路状态推送消息。");

            string requestMsg = triggerEvent.Message;
            if (string.IsNullOrEmpty(requestMsg))
            {
                return;
            }

            Dictionary<string, string> msgDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(requestMsg);
            if (msgDict == null || msgDict.Count == 0)
            {
                return;
            }

            // 流水号
            if (msgDict.ContainsKey("nonce"))
            {
                this.currentCallNonce = msgDict["nonce"];
            }

            // 主叫号码
            if (msgDict.ContainsKey("callNo"))
            {
                this.phoneNumber = msgDict["callNo"];
            }

            // 电话进度，1：振铃， 2：通话，3：通话结束
            if (msgDict.ContainsKey("eventType"))
            {
                string eventType = msgDict["eventType"];
                switch(eventType)
                {
                    case "1":
                        
                        break;

                    case "2":
                        isBusy = true;
                        AppendMessage("通话中...");
                        break;

                    case "3":
                        isBusy = false;
                        AppendMessage("通话结束...");
                        this.BeginInvoke((MethodInvoker)delegate
                        {
                            txtIncomingTel.Text = "";
                        });

                        break;
                }

                // 录音文件
                if (msgDict.ContainsKey("recordFile") && !string.IsNullOrEmpty(msgDict["recordFile"]))
                {
                    AppendMessage($"录音文件：{msgDict["recordFile"]}");
                }
            }
        }
    }
}
